package com.pic.mgt.monitor.parser.haishin;

import java.util.LinkedList;
import java.util.List;

import com.pic.mgt.monitor.WrongUnitFormatException;
import com.pic.mgt.monitor.parser.FormatParser;

public final class SimpleAppointedTerminalsParser extends FormatParser {
	private int appointedTerminalLength;
	
	private final String terminalListEofString = "<EOF>";
	
	
	@Override
	public List<String> parse(Object _terminals)
					throws WrongUnitFormatException {
		// 確認是否為 String[] 型態
		// throws WrongUnitFormatException
		super.checkObjectType(_terminals, String[].class);
		
		String[] terminals = (String[])_terminals;
		
		List<String> terminalList = new LinkedList<String>();
		
		boolean isEofStringExisted = false; // 檢查端末清單結尾字串是否存在
		
		// 檢查端末長度
		for(String terminal : terminals) {
			terminal = terminal.trim();
			if (terminal.equals(this.terminalListEofString)) {
				// 表示為結尾字串
				isEofStringExisted = true;
				break;
			}
			else if (terminal.length() == this.appointedTerminalLength) {
				terminalList.add(terminal);
			}
			else {
				throw new WrongUnitFormatException(
						"The terminal '" + terminal + "' length is invalid.");
			}
		}
		
		if (terminalList.size() == 0 || 
			!isEofStringExisted) {
			throw new WrongUnitFormatException(
				"The appointed terminals content is invalid.");
		}
		else {
			return terminalList;
		}
	}

	public void setAppointedTerminalLength(int appointedTerminalLength) {
		this.appointedTerminalLength = appointedTerminalLength;
	}
}
